<?php
namespace app\store\model;
use app\common\model\Calling as CallingModel;
use app\common\library\calling\HeMa;
use think\Db;

/**
 * 呼叫器模型
 */
class Calling extends CallingModel
{
	
    /**
	 * 用户设备绑定
     */
    public function add($data)
    {
    	if(strlen($data['device_name'])!= 8){
			$this->error = '设备编号应该为8位';
			return false;
		}
		if(strlen($data['device_key'])!= 16){
			$this->error = '设备密钥应该为16位';
			return false;
		}
		// 开启事务
        Db::startTrans();
        try {
			$call = new HeMa();
			if($err = $call->add($data)){
				$this->error = $err;
				return false;
			}
            if($data['volume'] < 15){
                $this->push('volume',$data['device_name'],$data['volume']);
            }
			$data['wxapp_id'] = self::$wxapp_id;
			$this->save($data);
			Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

    /**
     * 更新
     */
    public function edit($data)
    {
        $data['device_name'] = $this->device_name;
        $data['device_key'] = $this->device_key;
        $call = new HeMa();
        if($err = $call->edit($data)){
            $this->error = $err;
            return false;
        }
        if($data['volume'] != $this->volume['value']){
            $this->push('volume',$this->device_name,$data['volume']);
        }
        return $this->save($data) !== false;
    }

    /**
     * 删除
     */
    public function remove() 
    {
        $call = new HeMa();
        if($err = $call->delete($this->device_name)){
            $this->error = $err;
            return false;
        }
		return $this->delete();
    }
}
